package com.lin.missyou.service;

import com.lin.github.wxpay.sdk.WXPay;
import com.lin.github.wxpay.sdk.WXPayUtil;
import com.lin.missyou.core.enumeration.OrderStatus;
import com.lin.missyou.exception.http.ServerErrorException;
import com.lin.missyou.model.Order;
import com.lin.missyou.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author gcq
 * @Create 2021-11-22
 */
@Service
public class WxPaymentNotifyService {

    @Autowired
    private WxPaymentService wxPaymentService;

    @Autowired
    private OrderRepository orderRepository;

    @Transactional
    public void processPayNotify(String data)
    {
        Map<String, String> dataMap = new HashMap<>();
        try {
            dataMap = WXPayUtil.xmlToMap(data);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
        // 获取 wxPay
        WXPay wxPay = wxPaymentService.assmbleWxPayConfig();
        boolean valid;
        try {
            // 验证 sign 是否有效
            valid  = wxPay.isResponseSignatureValid(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }

        if(!valid)
        {
            throw new ServerErrorException(9999);
        }
        String returnCode = dataMap.get("return_code");
        String orderNo = dataMap.get("out_trade_no");
        String resultCode = dataMap.get("result_code");

        if(!returnCode.equals("SUCCESS"))
        {
            throw new ServerErrorException(9999);
        }

        if(!resultCode.equals("SUCCESS"))
        {
            throw new ServerErrorException(9999);
        }

        if(orderNo == null)
        {
            throw new ServerErrorException(9999);
        }

        this.deal(orderNo);
    }

    private void deal(String orderNo)
    {
        Optional<Order> orderOptional = this.orderRepository.findFirstByOrderNo(Long.parseLong(orderNo));
        Order order = orderOptional.orElseThrow(() -> new ServerErrorException(9999));
        /**
         * 订单状态扣除
         */
        // unpaid -> paid
        if(order.getStatus().equals(OrderStatus.UNPAID.value()))
        {

        }
        this.orderRepository.updateStatusByOrderNo(orderNo, OrderStatus.PAID.value());
    }
}